import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;

/**
 * Class to contain return packet from a node registration.
 * 
 * @author James Marquardt
 * @author Matt Adams
 * @author Justin Wong
 *
 */
public class RegistrationPacket implements Serializable {
	/**
     * 
     */
    private static final long serialVersionUID = 6294588862540627364L;
    /**
	 * The m value of the chord this node is registered to.
	 */
	public final int m_value;
	/**
	 * The id assigned to the registered node.
	 */
	public final int node_id;
	
	/**
	 * Arbitrary initial node reference.
	 */
	public final HostPort successorNodeReference;
	
	public final HostPort predecessorNodeReference;
	
	public final byte[] fingertable;

	
	/**
	 * Constructor for a RegistrationPacket
	 * 
	 * @param the_mappings The mappings of all nodes in the system.
	 * @param the_m_value The m value of the system.
	 * @param the_node_id The id of the registered node.
	 */
	public RegistrationPacket(HashMap<Integer, HostPort> fingers, final HostPort successorNodeReference,
								final HostPort predecesorNodeReference,
								final int the_m_value, final int the_node_id) {

		this.successorNodeReference = successorNodeReference;
	    this.predecessorNodeReference = predecesorNodeReference;
		m_value = the_m_value;
		node_id = the_node_id;
		
		byte[] fing = null;
		
		try {
			fing = toBytes(fingers);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		fingertable = fing;

	}
	
	/**
	 * Static method to serialize a hashmap.
	 * 
	 * @param o
	 * @return
	 * @throws IOException
	 */
	private static byte[] toBytes(Object o) throws IOException {
	    ByteArrayOutputStream baos = new ByteArrayOutputStream();
	    ObjectOutputStream oos = new ObjectOutputStream(baos);
	    oos.writeObject(o);
	    oos.close();
	    return baos.toByteArray();
	}
}
